package com.zhugang.week02;

/**
 * @program algorithms
 * @description: removeNthFromEnd
 * @author: chanzhugang
 * @create: 2022/05/31 15:36
 */
public class RemoveNthFromEnd {

    /**
     * 19. 删除链表的倒数第N个结点
     *
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // 遍历快指针先到第n个节点， 遍历pre， 删除倒数第n个节点
        ListNode fast = head;
        int count = 0;
        while (fast != null) {
            count++;
            if (count == n) {
                break;
            }
            fast = fast.next;
        }
        if (fast == null) {
            // 节点个数不够n个
            return head;
        }

        ListNode slow = head;
        ListNode pre = null;
        while (fast.next != null) {
            fast = fast.next;
            pre = slow;
            slow = slow.next;
        }
        if (pre == null) {
            // 头节点是倒数第n个节点
            head = head.next;
        } else {
            pre.next = slow.next;
        }
        return head;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}